package com.demo.enhance;

import java.lang.reflect.Method;
import java.util.List;

public class ReflectionMethodInvocation implements ProxyMethodInvocation{

    private final Object target;
    private final Object proxy;
    private final Method method;
    private Object[]args;
    private List<AopMethodInterceptor> proxyChain;
    public ReflectionMethodInvocation(Object target, Object proxy, Method method, Object[] args, List<AopMethodInterceptor> proxyChain) {
        this.target = target;
        this.proxy = proxy;
        this.method = method;
        this.args = args;
        this.proxyChain = proxyChain;
    }
    private Integer currentChainIndex = -1;

    @Override
    public Object proceed() throws Throwable{
        if(proxyChain!=null&&proxyChain.size()>0){
            // 执行真实的方法
            if(currentChainIndex==this.proxyChain.size()-1){
                return method.invoke(target,args);
            }
            //执行aop代理功能的方法，带有@Around注解的
            AopMethodInterceptor interceptor = proxyChain.get(++currentChainIndex);
            return interceptor.invoke(this);//递归的执行 该方法
        }else {//执行原始方法
            return method.invoke(target,args);
        }
    }


    @Override
    public Object getThis() {
        return this.target;
    }

    @Override
    public Method getMethod() {
        return this.method;
    }

    @Override
    public Object getProxyObject() {
        return this.proxy;
    }

    @Override
    public Object[] getArgs() {
        return args;
    }
}
